﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twlib;
using System.Net;
using System.Net.Sockets;

namespace TeamWork_Client
{
    public partial class RegisterSub : Form
    {
        public RegisterSub()
        {
            InitializeComponent();
        }

        private void commandLink1_Click(object sender, EventArgs e)
        {
            try
            {
                Socket s = new Socket(SocketType.Stream, ProtocolType.Tcp);
                s.Connect(IPAddress.Parse(textBox1.Text), 5522);
                UserCommand cmd = new UserCommand("/registersub", null, long.Parse(textBox3.Text));
                s.SendBufferSize = 30 * 1024;
                s.ReceiveBufferSize = 30 * 1024;
                Q1.RRR.BasicQ1BinaryFormation bmft = new Q1.RRR.BasicQ1BinaryFormation();
                byte[] b = Serialization.BinarySerialize(cmd);
                s.Send(bmft.Patch(b));
                byte[] bts = new byte[30 * 1024];
                s.Receive(bts);
                bts = bmft.DePatch(bts);
                ServerResponse res = (ServerResponse)Serialization.BinaryDeserialize(bts);
                if (res.OK)
                {
                    textBox2.Text = res.ResponseString;
                }
                else
                {
                    textBox2.Text = "Server Error: Unkown Exception.";
                }
            }catch(Exception ex)
            {
                if(ex is SocketException)
                {
                    MessageBox.Show("A socket error has been caught! Please make sure that your connection is still available or that the server is up.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
